// chat.js

var loading = 0;
var running = true;

function $(id) {
	return document.getElementById(id);
}

function execute(user, msgtype, msg) {
	msg = msg || "";
	msgtype = msgtype || "";
	var xhr = new XMLHttpRequest();
	xhr.open("get", "chat.php?user=" + user + "&msgtype=" + msgtype + "&msg=" + msg + "&timeStamp=" + new Date().getTime(), true);
	xhr.onreadystatechange = function() {
		if(xhr.readyState != 4 || xhr.status != 200) return ;
		--loading;
		var res = xhr.responseText;
		if(res != '') {
			console.log(res);
			try {
				var json = eval('(' + res + ')');
				$('msgs').innerHTML += ['<br />', 
					'<span class="time"> ', json['time'], ' </span>',
					'<span class="from">', json['from'], ': </span>',
					'<span class="msg">', json['msg'], '</span>'].join("");
			} catch(e) {
				console.warn('get illformat response text:', res);	
			}
		}
		if(loading == 0 && running)
			execute(user, null, null);
	}
	xhr.send(null);
	++loading;
}

function send() {
	running = true;
	if($('msg').value == '') return false;
	execute($('user').value, null, $('msg').value);
	$('msg').value = '';
	return false;
}

function userLeave() {
	running = false;
	execute($('user').value, "leave");
}

// scroll msg box
function scrollMsgbox() {
	$('msgs').scrollTop = $('msgs').scrollHeight - $('msgs').offsetHeight;	
}

window.onload = function() {
	setInterval(scrollMsgbox, 100, false);
}


